package com.yishan.security.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yishan.security.config.RedisPrefix;
import com.yishan.security.domain.LoginUser;
import com.yishan.security.domain.ResponseResult;
import com.yishan.security.domain.User;
import com.yishan.security.service.LoginService;
import com.yishan.security.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author: yishan
 * @Date: 2022/8/30 10:17
 **/
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult login(User user) {

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("账号或密码错误！请重试！");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        stringRedisTemplate.opsForValue().set(RedisPrefix.LOGIN_USER + userId, JSONObject.toJSONString(loginUser), 5, TimeUnit.HOURS);
        Map<String, String> resMap = new HashMap<>();
        resMap.put("token", jwt);
        return new ResponseResult(200, "登录成功！", resMap);

    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        stringRedisTemplate.delete(RedisPrefix.LOGIN_USER + userId);
        return new ResponseResult(200, "退出成功！");
    }
}
